
/** easyui数据表格*/

/**
 * 通用表格
 * id  元素唯一属性
 * options 基础配置, {}
 * buttonsIdx  索引：工具栏按钮配置(快速配置),[0,1,2,3,...]
 * buttonsFunc 事件：工具栏按钮配置(快速配置),[func1,func2,func3,..]
 */
zUtil.tableInit = function(id,options,buttonsIdx,buttonsFunc){
    var bts = [{
//        iconCls: 'fa fa-plus ',
        text:'新增',
        id:'z-table-add',//0
//        handler: function(){alert("新增");}
    },{
//        iconCls: 'fa fa-pencil',
        text:'编辑',
        id:'z-table-edit',//1
//        handler: function(){alert("编辑");}
    },{
//        iconCls: 'fa fa-file-text-o',
        text:'详情',
        id:'z-table-detail',//2
//        handler: function(){alert("详情");}
    },{
//        iconCls: 'fa fa-trash-o',
        text:'删除',
        id:'z-table-del',//3
//        handler: function(){alert("删除");}
    },{
//        iconCls: 'fa fa-search',
        text:'查询',
        id:'z-table-query',//4
//        handler: function(){alert("查询");}
    },{
//        iconCls: 'fa fa-search-plus',
        text:'高级查询',
        id:'z-table-queryx',//5
//        handler: function(){alert("高级查询");}
    },{
//        iconCls: 'fa fa-save',
        text:'确认',
        id:'z-table-ok',//6
//        handler: function(){alert("确认");}
    },{
//        iconCls: 'fa fa-reply',
        text:'撤销',
        id:'z-table-cancel',//7
//        handler: function(){alert("取消");}
    },{
//        iconCls: 'fa fa-reply',
        text:'清空选择',
        id:'z-table-clearselect',//8
//        handler: function(){alert("取消");}
    }];
    
    var newbts = [];
    if('undefined' !== $.type(buttonsIdx) && buttonsIdx != null){
        for (var i=0,ln = buttonsIdx.length ;i< ln; i++) {
            var tmp = bts[buttonsIdx[i]];
            if(buttonsFunc && buttonsFunc[i]){
                tmp.handler = buttonsFunc[i];
            }
            newbts.push(tmp);
/*            if(i<ln -1){//间隔
                newbts.push('-');
            }*/
        }
    }
    var opts = $.extend(true,{
//       url:'',
//       data : localdata,
         method: "get",
         queryParams:{},
         border: false,
         height: '100%',
         width: '100%',
         minHeight:'300px',
         nowrap: true, //true则把数据显示在一行里
         autoRowHeight: false,//true基于该行内容的行高度
         striped: true, //true行条纹化
         scrollbarSize: 5,//滚动条宽度
//       fitColumns: true, //设置为 true，则会自动扩大或缩小列的尺寸以适应网格的宽度并且防止水平滚动。
    //   rownumbers:true, //true行号
         singleSelect: true, //false单选
//         checkOnSelect: true, //true点击了复选框时，才会选中/取消
//         selectOnCheck: true, //true点击复选框将会选中该行
         pagination: true, //true分页
         pageNumber: 1,
         pageSize: 20,
         pageList:[20,40,60,80,100],
//         toolbar: [], //或'#tb'
         remoteSort: true, //服务器排序
//         sortName: null //string定义可以排序的列。
         sortOrder: 'asc',
         idField: null,  //主键
         columns:[[]],
//         frozenColumns:[[]],
//          onClickRow: function(rowIndex, rowData){},
//          onDblClickRow: function(rowIndex, rowData){},
//          onSelect: function(rowIndex, rowData){},
//          onUnselect: function(rowIndex, rowData){},
//          onCheck: function(rowIndex, rowData){},
//          onUncheck: function(rowIndex, rowData){},
//         onHeaderContextMenu: function(e, field){},//右键表头事件
//         onRowContextMenu: function(e, rowIndex, rowData){},//右键行事件
//           onSortColumn: function(sort, order){},//当用户对一列进行排序时触发
//         loader: function(param, success, error){},
         loadFilter: function(data){
            var tmp = {rows:[],total:0};
            try{//解析不了就原样返回
                tmp.rows = data[zConst["resData"]][zConst["data"]];
                tmp.total = data[zConst["resData"]][zConst["count"]];
            }catch(b){
                return data;
            }
            return tmp;
         },
         onBeforeLoad: function(param){
             var pager = $(id).datagrid("getPager");
             if(pager){
                 pager.pagination({
                     layout:['list','prev','manual','next','refresh',"info"],
                     displayMsg: '{from} - {to} of {total}',
                     beforePageText:null,
                     afterPageText:'/{pages}',
                 });
             }
             try{//解析不了就原样返回
                 param[zConst["page"]] = param.page;
                 param[zConst["rows"]] = param.rows;
             }catch(b){
                 return param;
             }
             return param;
         },
     },options);
    
    if('undefined' !== $.type(options.toolbar) && 'string' !== $.type(options.toolbar)){
        newbts = $.merge(newbts ,options.toolbar);
    }
    if('string' !== $.type(options.toolbar)){
        if(newbts.length > 0){
            opts.toolbar = newbts;
        }else{
            opts.toolbar = "";
        }
    }
    
    
    return $(id).datagrid(opts);
};

zUtil.tableInit2 = function(id,options,buttonsIdx,buttonsFunc){
    var opts = $.extend(true,{
         pagination: false,
    },options);
    zUtil.tableInit(id,opts,buttonsIdx,buttonsFunc);
};
zUtil.tableInitPost = function(id,options,buttonsIdx,buttonsFunc){
    var opts = $.extend(true,{
        method: "post",
    },options);
    zUtil.tableInit(id,opts,buttonsIdx,buttonsFunc);
};
/**
 * 查询/刷新列表
 * id 唯一属性
 * params 查询条件等{}
 * options 属性
 * */
zUtil.tableQuery = function(id,params,options){
    var pars = $.extend(true,{},params);
    if(options){
        var opts = $(id).datagrid("options");//获取 option设置对象
        $.extend(true,opts,options);
    }
    return $(id).datagrid('load',pars);
};
/**
 * 本地数据填充
 * id 唯一属性
 * data 数据
 * */
zUtil.tableData = function(id,data){
    if('undefined' !== $.type(data)){
        return $(id).datagrid("loadData",data);
    }else{
        return $(id).datagrid("getData"); 
    }
};
/**返回选中数据*/
zUtil.tableRows = function(id){
    var opts = $(id).datagrid("options");//获取 option设置对象
    if(opts.singleSelect){
        return $(id).datagrid('getSelected');
    }else{
        return $(id).datagrid('getSelections');
    }
};
/**选中行*/
zUtil.tableSelected = function(id,idx){
    var opts = $(id).datagrid("options");//获取 option设置对象
    if('number' === $.type(idx)){
        if(opts.selectOnCheck){
            return $(id).datagrid('selectRow',idx);
        }else{
            return $(id).datagrid('checkRow',idx);
        }
    }else if('undefined' !== $.type(idx)){
        return $(id).datagrid('selectRecord',idx);
    }else{
        if(opts.selectOnCheck){
            return $(id).datagrid('selectAll');
        }else{
            return $(id).datagrid('checkAll');
        }
    }
};
/**清除选中行*/
zUtil.tableUnSelected = function(id,idx){
    var opts = $(id).datagrid("options");//获取 option设置对象
    if("undefined" !== $.type(idx)){
        if(opts.selectOnCheck){
          return $(id).datagrid('unselectRow',idx);//取消选中一行
        }else{
          return $(id).datagrid('uncheckRow',idx);//取消选中一行
        }
    }else if('undefined' === $.type(idx)){
        return $(id).datagrid('clearSelections');
    }else{
        if("S1" === idx){
            return $(id).datagrid('clearChecked');//清除所有勾选的行
        }else if("S2" === idx){
            return $(id).datagrid('unselectAll');//取消选中当前页所有的行
        }
    }
};
/**分页处理*/
zUtil.tablePage = function(id,data,options){
    var pager = $(id).datagrid('getPager');
    if('undefined' !== $.type(data) && data['rows'] && data['total']){
        var dt = {total:data['total'],rows:[]};
        pager.pagination({
            onSelectPage:function(pageNumber, pageSize){
                $(this).pagination('loading');
                var t = data['rows'];
                if(pageNumber * pageSize <= t.length){
                    dt['rows'] = t.slice((pageNumber-1)*pageSize, pageNumber*pageSize);
                }else{
                    dt['rows'] = t.slice((pageNumber-1)*pageSize, t.length);
                }
                $(id).datagrid('loadData', dt);//AJAX分页加载数据本地填充
                $(this).pagination('loaded');
            }
        });
    }
    return pager;
};

/**table表头键菜单*/
var LAST_MENU_POSTION = null;
zUtil.tableHeaderMenu = function(e,menuObj,tableid){
    e.preventDefault();
    var showcss = 'glyphicon glyphicon-ok text-primary';
    var hidecss = 'glyphicon glyphicon-remove text-muted';
    if (!menuObj){
        menuObj = $('<div class="table-rmenu"/>').appendTo('body');
        menuObj.on("click",".menu-item", function(e){
            LAST_MENU_POSTION = menuObj[0].scrollTop;
        });
        menuObj.menu({
//            hideOnUnhover: false,
            onClick: function(item){
//                event.stopPropagation();
                var iobj = $(item.target);
                if (item.iconCls == showcss){
                    $(tableid).datagrid('hideColumn', item.name);
                    menuObj.menu('setIcon', {
                        target: item.target,
                        iconCls: hidecss, //icon-empty
                    });
                } else {
                    $(tableid).datagrid('showColumn', item.name);
                    menuObj.menu('setIcon', {
                        target: item.target,
                        iconCls: showcss,
                    });
                }
                menuObj.menu('show');
                var scrollTopMax = menuObj.children('.menu-item').length*iobj.outerHeight() - menuObj.innerHeight()+ parseInt(menuObj.css("padding-left"))*2;
//                console.log(menuObj.children('.menu-item').length +"--"+menuObj.innerHeight()/iobj.outerHeight()
//                         +"--"+scrollTopMax+"--"+LAST_MENU_POSTION +"--"+(scrollTopMax-LAST_MENU_POSTION));
                if(LAST_MENU_POSTION<=scrollTopMax+1){
                     menuObj.animate({scrollTop: LAST_MENU_POSTION}, 0);
                }
            }
        });
        var fields = $(tableid).datagrid('getColumnFields');
        for(var i=0; i<fields.length; i++){
            var field = fields[i];
            if(!field || field.trim() === "" || field.trim() === "_blank" ){
                continue;
            }
            var col = $(tableid).datagrid('getColumnOption', field);
            menuObj.menu('appendItem', {
                text: col.title,
                name: field,
                iconCls: col.hidden? hidecss : showcss
            });
        };
    }
    menuObj.menu('show', {
        left:e.pageX,
        top:e.pageY
    });
    return menuObj;
}
zUtil.table = function(id,type,obj){
    if('undefined' !== $.type(type)){
        if('number' === $.type(type)){
            type = type.toString();
        }
        if("selectr"=== type){
            /**选中行,更据记录唯一ID*/
            return $(id).datagrid('selectRecord',obj);//idValue
        }
        else if("updrow"=== type){
            /**行更新 {index: 2,row: {}}*/
            return $(id).datagrid('updateRow',obj);//editIdx
        }else if("rfhrow"=== type){
            /**行刷新*/
            return $(id).datagrid('refreshRow',obj);//editIdx
        }else if("apdrow"=== type){
            /**行新增*/
            return $(id).datagrid('appendRow',obj);//row
        }else if("delrow"=== type){
            /**行删除*/
            return $(id).datagrid('deleteRow',obj);//editIdx
        }else if("rejecte"=== type){
            /**编辑拒绝修改*/
            return $(id).datagrid('rejectChanges');
        }else if("accepte"=== type){
            /**编辑接受*/
             return $(id).datagrid('acceptChanges');
        }
        else if("cancele"=== type){
            /**行编辑撤销*/
            return $(id).datagrid('cancelEdit',obj);//editIdx
        }else if("ende"=== type){
            /**结束编辑*/
            return $(id).datagrid('endEdit',obj);//editIdx
        }else if("begine"=== type){
            /**开启编辑*/
            return $(id).datagrid('beginEdit',obj);//editIdx
        }else if("vldrow"=== type){
            /**编辑行校验*/
            return $(id).datagrid('validateRow',obj);//editIdx
        }else if("getidx"=== type){
            /**获取行索引*/
            return $(id).datagrid('getRowIndex',obj);//row
        }else if("getrows"=== type){
            /**获取当页所有行*/
            return $(id).datagrid('getRows');
        }else if("resize"=== type){
            /** 重置列表尺寸 params 参数*/
            var opts = $.extend(true,{},obj);
            return $(id).datagrid("resize",opts);
        }else if("opts"=== type){
            //获取 option设置对象
            return $(id).datagrid("options");
        }else if("getEditors" === type){
            //id
            return $(id).datagrid("getEditors",obj);
        }
    }
};

zUtil.ppGridInit = function(id,options){
    var opts = $.extend(true,{
        showGroup: true,//显示属性组
//        showHeader:false,
        scrollbarSize: 0,
        method:"GET",
        height: '100%',
//        width: '100%',
        nowrap: true, //true则把数据显示在一行里
        autoRowHeight: false,//true基于该行内容的行高度
//        striped: true, //true行条纹化
        data : [[]],
//        groupField: "", 定义组的字段名。
//        groupFormatter: function(group,rows){},
        columns:[[{field:'name',title:'属性名',width:'100',sortable:true,resizable:true},
                 {field:'value',title:'属性值',width:'100'},
                 ]],//sortable:true/resizable:true
        },options);
   return $(id).propertygrid(opts);
}

/**树形表格*/
zUtil.treegridInit = function(id,options,buttonsIdx,buttonsFunc){
    var bts = [{
//        iconCls: 'fa fa-plus ',
        text:'新增',
        id:'z-table-add',//0
//        handler: function(){alert("新增");}
    },{
//        iconCls: 'fa fa-pencil',
        text:'编辑',
        id:'z-table-edit',//1
//        handler: function(){alert("编辑");}
    },{
//        iconCls: 'fa fa-file-text-o',
        text:'详情',
        id:'z-table-detail',//2
//        handler: function(){alert("详情");}
    },{
//        iconCls: 'fa fa-trash-o',
        text:'删除',
        id:'z-table-del',//3
//        handler: function(){alert("删除");}
    },{
//        iconCls: 'fa fa-search',
        text:'查询',
        id:'z-table-query',//4
//        handler: function(){alert("查询");}
    },{
//        iconCls: 'fa fa-search-plus',
        text:'高级查询',
        id:'z-table-queryx',//5
//        handler: function(){alert("高级查询");}
    },{
//        iconCls: 'fa fa-save',
        text:'确认',
        id:'z-table-ok',//6
//        handler: function(){alert("确认");}
    },{
//        iconCls: 'fa fa-reply',
        text:'撤销',
        id:'z-table-cancel',//7
//        handler: function(){alert("取消");}
    }];
    
    var newbts = [];
    if('undefined' !== $.type(buttonsIdx) && buttonsIdx != null){
        for (var i=0,ln = buttonsIdx.length ;i< ln; i++) {
            var tmp = bts[buttonsIdx[i]];
            if(buttonsFunc && buttonsFunc[i]){
                tmp.handler = buttonsFunc[i];
            }
            newbts.push(tmp);
/*            if(i<ln -1){//间隔
                newbts.push('-');
            }*/
        }
    }
    var opts = $.extend(true,{
//       url:'',
//       data : localdata,
         method: "get",
         queryParams:{},
         border: false,
         height: '100%',
         width: '100%',
         nowrap: true, //true则把数据显示在一行里
         autoRowHeight: false,//true基于该行内容的行高度
         striped: true, //true行条纹化
         scrollbarSize: 5,//滚动条宽度
//       fitColumns: true, //设置为 true，则会自动扩大或缩小列的尺寸以适应网格的宽度并且防止水平滚动。
    //   rownumbers:true, //true行号
         singleSelect: true, //false单选
//         checkOnSelect: true, //true点击了复选框时，才会选中/取消
//         selectOnCheck: true, //true点击复选框将会选中该行
         pagination: true, //true分页
         pageNumber: 1,
         pageSize: 20,
         pageList:[20,40,60,80,100],
//         toolbar: [], //或'#tb'
         remoteSort: true, //服务器排序
//         sortName: null //string定义可以排序的列。
         sortOrder: 'asc',
         idField: 'idCode',
         treeField: 'treeCode',
         columns:[[]],
//         frozenColumns:[[]],
//          onClickRow: function(row){},
//          onDblClickRow: function(row){},
         loadFilter: function(data){
            var tmp = {rows:[],total:0};
            try{//解析不了就原样返回
                tmp.rows = data[zConst["resData"]][zConst["data"]];
                tmp.total = data[zConst["resData"]][zConst["count"]];
            }catch(b){
                return data;
            }
            return tmp;
         },
         onBeforeLoad: function(param){
             try{//解析不了就原样返回
                 param[zConst["page"]] = param.page;
                 param[zConst["rows"]] = param.rows;
             }catch(b){
                 return param;
             }
             return param;
         },
     },options);
    
    if('undefined' !== $.type(options.toolbar) && 'string' !== $.type(options.toolbar)){
        newbts = $.merge(newbts ,options.toolbar);
    }
    if('string' !== $.type(options.toolbar)){
        if(newbts.length > 0){
            opts.toolbar = newbts;
        }else{
            opts.toolbar = "";
        }
    }
    
    
    return $(id).treegrid(opts);
}
zUtil.treegridInit2 = function(id,options,buttonsIdx,buttonsFunc){
    var opts = $.extend(true,{
         pagination: false,
    },options);
    zUtil.treegridInit(id,opts,buttonsIdx,buttonsFunc);
};
zUtil.treegrid = function(id,type,obj){
    if('undefined' !== $.type(type)){
        if('number' === $.type(type)){
            type = type.toString();
        }
        
        if("getdt" === type){
            return $(id).treegrid("getData");
        }else if("ldt" === type){
            return $(id).treegrid("loadData",obj);
        }else if("rld" === type){
            return $(id).treegrid("reload",obj);
        }else if("load" === type){
            return $(id).treegrid("load",obj);
        }else if("slt" === type){
            return $(id).treegrid("select",obj);//id
        }else if("ust" === type){
            return $(id).treegrid("unselect",obj);//id
        }else if("sta" === type){
            return $(id).treegrid("selectAll");
        }else if("usta" === type){
            return $(id).treegrid("unselectAll");
        }else if("getst" === type){
            return $(id).treegrid("getSelected");
        }else if("getsta" === type){
            return $(id).treegrid("getSelections");
        }else if("getprt" === type){
            return $(id).treegrid("getParent",obj);//id
        }else if("getcld" === type){
            return $(id).treegrid("getChildren",obj);//id
        }else if("getrt" === type){
            return $(id).treegrid("getRoot");
        }else if("getrts" === type){
            return $(id).treegrid("getRoots");
        }else if("getlvl" === type){
            //id
            return $(id).treegrid("getLevel",obj);
        }else if("find" === type){
            //id
            return $(id).treegrid("find",obj);
        }else if("rmv" === type){
            //id
            return $(id).treegrid("remove",obj);
        }else if("apd" === type){
            //{ parent: node.id, data: [{}]}
            return $(id).treegrid("append",obj);//追加
        }else if("ist" === type){
            //before/after,{ before: node.id, data: [{}]}
            return $(id).treegrid("insert",obj);
        }else if("upd" === type){
            //{ id: 2, row: {}}
            return $(id).treegrid("update",obj);
        }else if("rfh" === type){
            return $(id).treegrid("refresh",obj);
        }else if("begine" === type){
            //id
            return $(id).treegrid("beginEdit",obj);
        }else if("ende" === type){
            //id
            return $(id).treegrid("endEdit",obj);
        }else if("cancele" === type){
            //id
            return $(id).treegrid("cancelEdit",obj);
        }
        else if("getEditors" === type){
            //id
            return $(id).treegrid("getEditors",obj);
        }
        else if("getidx" === type){
            //id
            return $(id).treegrid("getRowIndex",obj);
        }
        
    }
}
/** 普通树初始化*/
zUtil.treeInit = function(id,options){
    //data格式[{}]
    //id：节点的 id
    //text：节点文本。
    //state：节点状态，'open' 或 'closed'，默认是 'open'
    //checked：指示节点是否被选中。
    //attributes：给一个节点添加的自定义属性。
    //children：子节点的节点数组。

    var opts = $.extend(true,{
      data:[],
      method:"GET",
      lines:true, //定义是否显示树线条
    //  formatter:function(node){return node.text;},
      loadFilter: function(data,parent){
          try{//解析不了就原样返回
              return  data[zConst["resData"]][zConst["data"]];
          }catch(b){
              return data;
          }
      },
    }, options);
    return $(id).tree(opts);
}
zUtil.tree = function(id,type,obj){
    if('undefined' !== $.type(type)){
        if('number' === $.type(type)){
            type = type.toString();
        }
        if("ck" === type){
            return $(id).tree("check",obj);//target
        }else if("unck" === type){
            return $(id).tree("uncheck",obj);//target
        }else if("getck" === type){
            return $(id).tree("getChecked",obj);//默认'checked'.'unchecked'、'indeterminate'
        }else if("getst" === type){
            return $(id).tree("getSelected");
        }else if("slt" === type){
            return $(id).tree("select",obj);//target
        }else if("getdt" === type){
            return $(id).tree("getData",obj);//target
        }else if("ldt" === type){
            return $(id).tree("loadData",obj);//data
        }else if("rld" === type){
            return $(id).tree("reload",obj);//target
        }else if("getnd" === type){
            return $(id).tree("getNode",obj);//target
        }else if("getprt" === type){
            return $(id).tree("getParent",obj);//target
        }else if("getcld" === type){
            return $(id).tree("getChildren",obj);//target
        }else if("getrt" === type){
            return $(id).tree("getRoot",obj);//nodeEl
        }else if("getrts" === type){
            return $(id).tree("getRoots");
        }else if("getlvl" === type){
            //id
            return $(id).tree("getLevel",obj);
        }else if("find" === type){
            //id
            return $(id).tree("find",obj);
        }else if("rmv" === type){
            //id
            return $(id).tree("remove",obj);
        }else if("apd" === type){
            //{ parent: node.id, data: [{}]}
            return $(id).tree("append",obj);//追加
        }else if("ist" === type){
            //before/after,{ before: node.id, data: [{}]}
            return $(id).tree("insert",obj);
        }else if("upd" === type){
            //{target（DOM 对象，要被更新的节点）、id、text、iconCls、checked，}
            return $(id).tree("update",obj);
        }else if("begine" === type){
            //target
            return $(id).tree("beginEdit",obj);
        }else if("ende" === type){
            //target
            return $(id).tree("endEdit",obj);
        }else if("cancele" === type){
            //target
            return $(id).tree("cancelEdit",obj);
        }
    }
}

/** zTree树初始化*/
zUtil.zTreeInit= function(id,options){
    var opts = $.extend(true,{
        check: {
            enable: true
           ,chkDisabledInherit: false
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        view: {
            nameIsHTML: true
        },
        callback: {
//             onClick : function(event, treeId, treeNode){}
//            ,onCheck: function(event, treeId, treeNode){}
        },
        treenodes:[]
    }, options);
    var zTree = $.fn.zTree.init($(id), opts, opts.treenodes);
    return zTree;
}
